const connect = require('connect');

const app = connect();
app.use(logger);
app.use('/admin', restrict);
app.use('/admin', admin);
app.listen(3000);

function logger(req, res, next) {
  console.log('%s %s', req.method, req.url);
  next();
}

function restrict(req, res, next) {
  const authorization = req.headers.authorization;
  if (!authorization) {
    return next(new Error('Unauthorized'));
  }

  const parts = authorization.split(' ');
  const scheme = parts[0];
  const auth = new Buffer(parts[1], 'base64').toString().split(':');
  const user = auth[0];
  const pass = auth[1];

  authorizateWithDatabase(user, pass, function (err) {
    if (err) {
      return next(err);
    }
    next();
  });
}

function admin(req, res, next) {
  switch (req.url) {
    case '/':
      res.end('try /users');
      break;
    case '/users':
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(['tobi', 'loke', 'jane']));
      break;
  }
}
